package com.lanyanhua.job.job;

import com.lanyanhua.job.entity.Result;
import lombok.extern.slf4j.Slf4j;

import java.util.Hashtable;
import java.util.Map;


/**
 * @Auther: lanyanhua
 * @Date: 2018/12/27 0027 13:23
 * @Description: 重写异常次数
 */
@Slf4j
public class EmailErrorCountJob extends ExecuteJob {

    private static Map<Integer, Integer> errorCount;

    /**
     * 判断是否发送邮件
     */
    @Override
    public boolean isSend() {
        if (super.isSend() && jobInfo.getEmailType() != null) {
            int count = errorCount.get(jobInfo.getJobId());
            return count >= jobInfo.getEmailType();
        }
        return false;
    }

    /**
     * 重写执行方法 计算失败次数
     */
    @Override
    public Result executeCall() {
        Result result = super.executeCall();
        addErrorCount(result);
        return result;
    }

    /**
     * 累加连续错误的次数
     */
    private void addErrorCount(Result result) {
        int count = 0;
        if (!result.isSuccess()) {
            if (errorCount.containsKey(jobInfo.getJobId())) {
                count = errorCount.get(jobInfo.getJobId());
            }
            count++;
        }
        errorCount.put(jobInfo.getJobId(), count);
    }

    static {
        errorCount = new Hashtable<>();
    }
}
